import {Component, OnInit, ViewChild} from '@angular/core';
import {FormBuilder, FormGroup} from '@angular/forms';
import {NzMessageService} from 'ng-zorro-antd/message';
import {ApplicationRecordService} from '../../service/application-record.service';
import {ApplicationRecordQueryForm} from '../../types/req/ApplicationRecordQueryForm';
import {SharedModule} from '../shared.module';
import {ApplicationRecord} from '../../types/resp/ApplicationRecord';
import {Page} from '../../types/page';
import {ApplicationRecordAddComponent} from './application-record-add.component';
import {ApplicationRecordViewComponent} from './application-record-view.component';
import {NzModalService} from 'ng-zorro-antd/modal';
import {EnterpriseSelectorComponent} from '../enterprise/enterprise-selector.component';
import {JobDescriptionSelectorComponent} from '../job-description/job-description-selector.component';
import {CandidateSelectorComponent} from '../candidate/candidate-selector.component';
import {CandidateViewAllComponent} from '../candidate/candidate-view-all.component';

@Component({
  selector: 'application-record-list',
  imports: [
    EnterpriseSelectorComponent,
    JobDescriptionSelectorComponent,
    CandidateSelectorComponent,
    ApplicationRecordAddComponent,
    ApplicationRecordViewComponent,
    CandidateViewAllComponent,
    SharedModule
  ],
  templateUrl: './application-record-list.component.html',
  standalone: true
})
export class ApplicationRecordListComponent implements OnInit {
  searchForm!: FormGroup;
  searchLoading: boolean = false
  listOfData: ApplicationRecord[] = [];
  total: number = 0
  disableFindCandidateFormItem: boolean = false

  @ViewChild(EnterpriseSelectorComponent, { static: false }) enterpriseSelectorComponent!: EnterpriseSelectorComponent;
  @ViewChild(JobDescriptionSelectorComponent, { static: false }) jobDescriptionSelectorComponent!: JobDescriptionSelectorComponent;
  @ViewChild(CandidateSelectorComponent, { static: false }) candidateSelectorComponent!: CandidateSelectorComponent;
  @ViewChild(CandidateViewAllComponent, { static: false }) candidateViewAllComponent!: CandidateViewAllComponent;
  @ViewChild(ApplicationRecordAddComponent, { static: false }) applicationRecordAddComponent!: ApplicationRecordAddComponent;
  @ViewChild(ApplicationRecordViewComponent, { static: false }) applicationRecordViewComponent!: ApplicationRecordViewComponent;

  constructor(
    private fb: FormBuilder,
    private message: NzMessageService,
    private applicationRecordService: ApplicationRecordService,
    private modal: NzModalService
  ) {}

  ngOnInit(): void {
    const type = sessionStorage.getItem('type')
    if (type && Number(type) === 3) {
      this.searchForm = this.fb.group({
        enterpriseId: [0],
        enterpriseName: [''],
        jobDescriptionId: [0],
        jobDescriptionName: [''],
        candidateId: [{value: 2, disabled: true}],
        candidateName: [{value: '陈静', disabled: true}],
        status: [undefined],
      })
      this.disableFindCandidateFormItem = true
    } else {
      this.searchForm = this.fb.group({
        enterpriseId: [0],
        enterpriseName: [''],
        jobDescriptionId: [0],
        jobDescriptionName: [''],
        candidateId: [0],
        candidateName: [''],
        status: [undefined],
      })
    }
    this.onSearch()
  }

  onReset() {
    this.searchForm.reset()
  }

  onSearch() {
    try {
      this.searchLoading = true
      this.applicationRecordService.find(new ApplicationRecordQueryForm(this.searchForm.getRawValue())).subscribe({
        next: (resp) => {
          if (!resp || resp.code !== 1) {
            this.message.error(resp && resp.msg ? resp.msg : '操作异常')
            return
          }
          const page: Page<ApplicationRecord> | undefined = resp.data
          if (page && page.list.length > 0) {
            this.listOfData = page.list
            this.total = page.total
          }
        },
        complete: () => {
          this.searchLoading = false
        }
      })
    } catch (e) {
      console.log('获取数据异常', e)
    }
  }

  onAdd() {
    this.applicationRecordAddComponent.display(0)
  }

  editRow(id: number) {
    this.applicationRecordAddComponent.display(id)
  }

  delRow(id: number) {
    this.modal.confirm({
      nzTitle: '<i>删除提示</i>',
      nzContent: '<b>确定要删除吗?</b>',
      nzOnOk: () => {
        this.applicationRecordService.del(id).subscribe({
          next: (resp) => {
            if (resp && resp.code === 1) {
              this.message.success('删除成功!')
              this.onSearch()
            } else {
              this.message.error('操作失败:' + (resp.msg ? resp.msg : '原因未知'))
            }
          },
          complete: () => {
            this.searchLoading = false
          }
        })
      }
    });
  }

  detailRow(record: ApplicationRecord) {
    this.applicationRecordViewComponent.display(record)
  }

  candidateRow(record: ApplicationRecord) {
    this.candidateViewAllComponent.display(record)
  };

  findEnterprise() {
    this.enterpriseSelectorComponent.display()
  }

  handleEnterpriseSelectedEvent(selectedEnterprise: { enterpriseId?: number; enterpriseName?: string; }) {
    if (selectedEnterprise && 'enterpriseId' in selectedEnterprise) {
      this.searchForm.patchValue(selectedEnterprise);
    }
  }

  findJobDescription() {
    this.jobDescriptionSelectorComponent.display()
  }

  handleJobDescriptionSelectedEvent(selectedJobDescription: { jobDescriptionId?: number; jobDescriptionName?: string; }) {
    if (selectedJobDescription && 'jobDescriptionId' in selectedJobDescription) {
      this.searchForm.patchValue(selectedJobDescription);
    }
  }

  findCandidate() {
    this.candidateSelectorComponent.display()
  }

  handleCandidateSelectedEvent(selectedCandidate: { candidateId?: number; candidateName?: string; }) {
    if (selectedCandidate && 'candidateId' in selectedCandidate) {
      this.searchForm.patchValue(selectedCandidate);
    }
  }

  onAdded(addedFlag: boolean) {
    if (addedFlag) {
      this.onSearch()
    }
  }
}
